import { _decorator, AudioClip, BoxCollider2D, Button, Component, Contact2DType, Director, director, dragonBones, ERigidBody2DType, find, instantiate, Label, Node, ParticleSystem2D, PolygonCollider2D, Prefab, resources, RigidBody2D, Sprite, SpriteFrame, Tween, tween, UIOpacity, UITransform, v2, v3 } from 'cc';
import { tagEnum } from './Enum';
import { getDistance, isNearlyEqual, randomNum, trackTarget } from './utils/utils';
import { UserInfo } from './UserInfo';
import { AudioMgr } from './utils/AudioMgr';
import { Adsdk } from './utils/Adsdk';
const { ccclass, property } = _decorator;

@ccclass('SingleGameMgr')
export class SingleGameMgr extends Component {

    @property(Node)
    player: Node;
    @property(Prefab)
    leftBlockPre: Prefab;
    @property(Prefab)
    rightBlockPre: Prefab;
    @property(Prefab)
    minTipPre: Prefab;
    @property(Node)
    gameRoot: Node;
    @property(Node)
    failPanel: Node;
    @property(Node)
    minTipRoot: Node;
    @property(Node)
    canvasMask: Node;
    @property([SpriteFrame])
    blockImgArr: SpriteFrame[] = [];
    @property(Label)
    playerScoreLabel: Label;
    @property(Node)
    pausePanel: Node;
    @property(AudioClip)
    scale_into: AudioClip;
    @property(AudioClip)
    scale_loop: AudioClip;

    static ins: SingleGameMgr = null;
    isClickIngBg = false;
    jumpTime = 1;//跳跃蓄力时间
    isJumpIng = false;
    isGameIng = true;
    isJudgeDrop = false;

    nextBlock: Node;//下一个格子

    leftPlayerStartWorldPos = v3(166, 502, 0);
    rightPlayerStartWorldPos = v3(575, 502, 0);

    currStandBlock = null;
    isMoveGameRootIng = false;

    playerDirection = 0;//0玩家朝右，1玩家朝左

    private playerScore = 0;
    get PlayerScore() {
        return this.playerScore;
    }
    set PlayerScore(value) {
        this.playerScore = value;
        this.playerScoreLabel.string = "得分：" + value;
    }

    protected onLoad(): void {
        SingleGameMgr.ins = this;
    }

    start() {
        //更换皮肤
        switch (UserInfo.p1SkinSelect) {
            case 0:
                this.player.getChildByName("sp").getComponent(dragonBones.ArmatureDisplay).armatureName = "player"
                break;
            case 1:
                this.player.getChildByName("sp").getComponent(dragonBones.ArmatureDisplay).armatureName = "playerGold"
                break;
            case 2:
                this.player.getChildByName("sp").getComponent(dragonBones.ArmatureDisplay).armatureName = "huahuaGold"
                break;
            case 3:
                this.player.getChildByName("sp").getComponent(dragonBones.ArmatureDisplay).armatureName = "jiewu"
                break;
            case 4:
                this.player.getChildByName("sp").getComponent(dragonBones.ArmatureDisplay).armatureName = "gongzhuDark"
                break;
            case 5:
                this.player.getChildByName("sp").getComponent(dragonBones.ArmatureDisplay).armatureName = "hongpi"
                break;

            default:
                this.player.getChildByName("sp").getComponent(dragonBones.ArmatureDisplay).armatureName = "player"
                break;
        }
        this.node.getChildByName("bg").on(Node.EventType.TOUCH_START, this.startTouch, this);
        this.node.getChildByName("bg").on(Node.EventType.TOUCH_END, this.endTouch, this);
        this.node.getChildByName("bg").on(Node.EventType.TOUCH_CANCEL, this.endTouch, this);


        this.player.getComponent(BoxCollider2D).on(Contact2DType.BEGIN_CONTACT, this.beginContact);
        this.currStandBlock = this.gameRoot.getChildByName("blockRoot").getChildByName("firstBlock");

        this.PlayerScore = 0;

        let dragonBonesComp = this.player.getChildByName("sp").getComponent(dragonBones.ArmatureDisplay);
        dragonBonesComp.playAnimation("land", 1);
        dragonBonesComp.addEventListener(dragonBones.EventObject.COMPLETE, () => {
            dragonBonesComp.playAnimation("stand", 1);
            this.canvasMask.active = false;

        }, this);

        // if (UserInfo.isAudioBgm) {
        //     AudioMgr.ins.play("audio/bgm")
        // }
        // else{
        AudioMgr.ins.stop();
        // }

        AudioMgr.ins.playOneShot("audio/start", 0.8);

        this.nextBlock = this.player.parent.getChildByName("blockRoot").getChildByName("rightBlockSingle");
    }
    gameReSet() {
        this.isClickIngBg = false;
        this.jumpTime = 1;
        this.isJumpIng = false;
        this.isMoveGameRootIng = false;
        this.isClickIngBgTempCount = 0;

        // this.playerDirection = 0;//0玩家朝右，1玩家朝左
        // this.playerDirection2 = 0;//0玩家2朝右，1玩家朝左
        // this.currStandBlock=this.gameRoot.getChildByName("blockRoot").getChildByName("firstBlock");
        // this.currStandBlock2=this.gameRoot2.getChildByName("blockRoot").getChildByName("firstBlock");
        // this.PlayerScore=0;
    }


    beginContact(self, other) {
        director.once(Director.EVENT_AFTER_PHYSICS, () => {

            if (other.tag == tagEnum.block) {
                if (other.node == SingleGameMgr.ins.currStandBlock) {
                    return;
                }

                SingleGameMgr.ins.player.getComponent(RigidBody2D).linearVelocity = v2(0, 0);
                SingleGameMgr.ins.player.getComponent(RigidBody2D).type = ERigidBody2DType.Kinematic;
                other.node.getComponent(PolygonCollider2D).enabled = false;
                other.node.getComponent(RigidBody2D).enabled = false;
                SingleGameMgr.ins.currStandBlock = other.node;
                SingleGameMgr.ins.isJudgeDrop = false;
                AudioMgr.ins.playOneShot("audio/playerJump", 0.8);
                let centerPos = other.node.getChildByName("centerPoint").getWorldPosition();
                let playerCenterPos = SingleGameMgr.ins.player.getChildByName("centerPoint").getWorldPosition();
                if (getDistance(centerPos.x, centerPos.y, playerCenterPos.x, playerCenterPos.y) < 15) {
                    console.log("完美跳跃")
                    AudioMgr.ins.playOneShot("audio/perfect", 0.7);
                    let dragonBonesComp = SingleGameMgr.ins.player.getChildByName("sp").getComponent(dragonBones.ArmatureDisplay);
                    let ani = dragonBonesComp.playAnimation("celebrate", 1);
                    ani.timeScale = 1.5

                    SingleGameMgr.ins.PlayerScore += 2;

                    console.log(other.node.getWorldPosition(), "other.node.getWorldPosition()")
                    let minTipPos = SingleGameMgr.ins.minTipRoot.getComponent(UITransform).convertToNodeSpaceAR(other.node.getWorldPosition());
                    SingleGameMgr.ins.createMinStr(minTipPos, "完美跳跃");

                }
                else {
                    SingleGameMgr.ins.PlayerScore += 1;
                }

                let randDir = randomNum(0, 1)
                if (randDir == 0) {
                    SingleGameMgr.ins.playerDirection = 1

                    SingleGameMgr.ins.player.scale = v3(-1, 1, 1)

                }
                else {
                    SingleGameMgr.ins.playerDirection = 0

                    SingleGameMgr.ins.player.scale = v3(1, 1, 1)
                }

                setTimeout(() => {
                    if (!SingleGameMgr.ins.isMoveGameRootIng) {
                        SingleGameMgr.ins.moveGameRoot();

                    }
                }, 1000)

            }

            if (other.tag == tagEnum.dieLine) {
                SingleGameMgr.ins.gameOver();
            }
        })
    }

    isPlayScaleAudio;
    startTouch() {
        console.log("点击")
        if (!this.isJumpIng) {
            this.isClickIngBg = true;

            this.isPlayScaleAudio = true;
            AudioMgr.ins.audioSource2.clip = this.scale_into;
            AudioMgr.ins.audioSource2.loop = false;
            AudioMgr.ins.audioSource2.volume = 0.8;
            AudioMgr.ins.audioSource2.play();
            // setTimeout(() => {
            //     if (this.isPlayScaleAudio) {
            //         AudioMgr.ins.audioSource2.clip=this.scale_loop;
            //         AudioMgr.ins.audioSource2.loop=true;
            //         AudioMgr.ins.audioSource2.volume=0.8;
            //         AudioMgr.ins.audioSource2.play();
            //     }
            // }, 2000);

            if (this.currStandBlock) {
                tween(this.currStandBlock.getChildByName("sp"))
                    .tag(42)
                    .by(2.5, { scale: v3(0, -0.4, 0), position: v3(0, -15, 0) })
                    .start()

                tween(this.player.getChildByName("sp"))
                    .tag(42)
                    .by(2.5, { position: v3(0, -45, 0), scale: v3(0, -0.2, 0) })
                    .start()
            }
            this.player.getChildByName("jumpParticle2D").getComponent(ParticleSystem2D).resetSystem();

        }
    }

    endTouch() {
        if (!this.isJumpIng) {
            this.isJumpIng = true;
            this.isPlayScaleAudio = false;
            AudioMgr.ins.audioSource2.stop();
            if (this.currStandBlock) {
                Tween.stopAllByTag(42);
                this.currStandBlock.getChildByName("sp").scale = v3(1, 1, 1);
                this.currStandBlock.getChildByName("sp").position = v3(0, 0, 0);
                this.player.getChildByName("sp").setPosition(0, 0, 0);
                this.player.getChildByName("sp").scale = v3(1, 1, 1);
            }
            this.player.getChildByName("jumpParticle2D").getComponent(ParticleSystem2D).stopSystem();

            this.player.getComponent(RigidBody2D).linearVelocity = v2(4, 9);
            if (this.playerDirection == 0) {
                this.player.getComponent(RigidBody2D).linearVelocity = v2(4 * this.jumpTime, 9 * this.jumpTime);
            }
            else {
                this.player.getComponent(RigidBody2D).linearVelocity = v2(-4 * this.jumpTime, 9 * this.jumpTime);
            }
            // if (this.playerDirection==0) {
            //     this.player.getComponent(RigidBody2D).linearVelocity = v2(6, 14);
            // }
            // else {
            //     this.player.getComponent(RigidBody2D).linearVelocity = v2(-6, 14);
            // }
            // this.player.getComponent(RigidBody2D).linearVelocity = v2(10, 24);
            this.player.getComponent(RigidBody2D).type = ERigidBody2DType.Dynamic;

            this.isClickIngBg = false;
            this.jumpTime = 1;
            this.isClickIngBgTempCount = 0;
            setTimeout(() => {
                this.isJudgeDrop = true;

            }, 500)


        }

    }

    //创建块
    createOneBloack() {
        if (this.playerDirection == 0) {//如果朝向是右边
            let pre = instantiate(this.rightBlockPre);
            pre.setParent(this.gameRoot.getChildByName("blockRoot"));

            let randSca = randomNum(0, 1)
            if (randSca == 0) {
                pre.scale = v3(1.5, 1.5, 1.5);
            }
            else {
                pre.scale = v3(1.35, 1.35, 1.35);
            }

            if (this.PlayerScore < 30) {
                pre.getChildByName("sp").getComponent(Sprite).spriteFrame = this.blockImgArr[0];
            }
            else if (this.PlayerScore >= 30 && this.PlayerScore < 60) {
                pre.getChildByName("sp").getComponent(Sprite).spriteFrame = this.blockImgArr[1];
            }
            else if (this.PlayerScore >= 60 && this.PlayerScore < 90) {
                pre.getChildByName("sp").getComponent(Sprite).spriteFrame = this.blockImgArr[2];
            }
            else {
                pre.getChildByName("sp").getComponent(Sprite).spriteFrame = this.blockImgArr[3];
            }

            let rand = randomNum(0, 1)
            // let rand = 1
            if (rand == 0) {
                pre.setWorldPosition(366, 640, 0);
            }
            else {
                pre.setWorldPosition(420, 710, 0);
            }
            pre.getComponent(UIOpacity).opacity = 0;
            tween(pre.getComponent(UIOpacity))
                .to(0.7, { opacity: 255 })
                .start()

            this.nextBlock = pre

        }
        else {
            let pre = instantiate(this.leftBlockPre);
            pre.setParent(this.gameRoot.getChildByName("blockRoot"));

            let randSca = randomNum(0, 1)
            if (randSca == 0) {
                pre.scale = v3(1.5, 1.5, 1.5);
            }
            else {
                pre.scale = v3(1.35, 1.35, 1.35);
            }

            if (this.PlayerScore < 30) {
                pre.getChildByName("sp").getComponent(Sprite).spriteFrame = this.blockImgArr[0];
            }
            else if (this.PlayerScore >= 30 && this.PlayerScore < 60) {
                pre.getChildByName("sp").getComponent(Sprite).spriteFrame = this.blockImgArr[1];
            }
            else if (this.PlayerScore >= 60 && this.PlayerScore < 90) {
                pre.getChildByName("sp").getComponent(Sprite).spriteFrame = this.blockImgArr[2];
            }
            else {
                pre.getChildByName("sp").getComponent(Sprite).spriteFrame = this.blockImgArr[3];
            }


            let rand = randomNum(0, 1);
            // let rand = 1

            if (rand == 0) {
                pre.setWorldPosition(366, 640, 0);
            }
            else {
                pre.setWorldPosition(320, 730, 0);
            }
            pre.getComponent(UIOpacity).opacity = 0;
            tween(pre.getComponent(UIOpacity))
                .to(0.7, { opacity: 255 })
                .start()

            this.nextBlock = pre

        }
    }
    moveGameRoot() {
        for (let i = 0; i < this.gameRoot.getChildByName("blockRoot").children.length; i++) {
            let block = this.gameRoot.getChildByName("blockRoot").children[i];
            if (block.getWorldPosition().x < -500 || block.getWorldPosition().x > 2000) {
                console.log("块销毁")
                block.destroy();
            }
            if (block.getWorldPosition().y < -500 || block.getWorldPosition().y > 2500) {
                console.log("块销毁")
                block.destroy();
            }

        }

        this.isMoveGameRootIng = true;
        if (this.playerDirection == 0) {
            let currBlockPos = this.currStandBlock.getWorldPosition();
            let dir = v2(currBlockPos.x - this.leftPlayerStartWorldPos.x, currBlockPos.y - this.leftPlayerStartWorldPos.y);
            let pos = this.gameRoot.getPosition();

            tween(this.gameRoot)
                .to(1, { position: v3(pos.x - dir.x, pos.y - dir.y, 0) })
                .call(() => {
                    this.createOneBloack();
                    this.isMoveGameRootIng = false;
                    this.isJumpIng = false;

                })
                .start()
        }
        else {
            let currBlockPos = this.currStandBlock.getWorldPosition();
            let dir = v2(currBlockPos.x - this.rightPlayerStartWorldPos.x, currBlockPos.y - this.rightPlayerStartWorldPos.y);
            let pos = this.gameRoot.getPosition();

            tween(this.gameRoot)
                .to(1, { position: v3(pos.x - dir.x, pos.y - dir.y, 0) })
                .call(() => {
                    this.createOneBloack();
                    this.isMoveGameRootIng = false;
                    this.isJumpIng = false;

                })
                .start()
        }

    }


    isClickIngBgTempCount = 0;
    tempPlayerPos = v3();
    tempPlayerPosPre = v3(0, 0, 0);
    tempBlockPos = v3();
    update(deltaTime: number) {
        if (this.isGameIng) {
            if (this.isClickIngBg) {
                this.isClickIngBgTempCount += deltaTime;

                if (this.isClickIngBgTempCount > 0.2) {
                    this.isClickIngBgTempCount = 0;
                    if (this.jumpTime < 2) {
                        this.jumpTime += 0.22;

                    }

                }

            }

            if (this.isJudgeDrop) {
                this.player.getWorldPosition(this.tempPlayerPos);
                if (this.tempPlayerPosPre != v3(0, 0, 0)) {
                    if (this.tempPlayerPos.y < this.tempPlayerPosPre.y) {
                        //下落

                        console.log("下落")
                        if (this.nextBlock) {
                            if (this.tempPlayerPos.y < this.nextBlock.getWorldPosition(this.tempBlockPos).y - 50) {
                                this.isJudgeDrop = false;
                                this.gameOver();
                            }
                        }

                    }
                }

                this.player.getWorldPosition(this.tempPlayerPosPre);
            }

        }

    }

    gameOver() {
        if (this.isGameIng) {
            SingleGameMgr.ins.player.getChildByName("sp").getComponent(dragonBones.ArmatureDisplay).playAnimation("die", 1);
            SingleGameMgr.ins.player.getComponent(RigidBody2D).linearVelocity = v2(0, 0);
            SingleGameMgr.ins.player.getComponent(RigidBody2D).type = ERigidBody2DType.Kinematic;
            AudioMgr.ins.playOneShot("audio/drop", 0.7);

            this.isGameIng = false;
            setTimeout(() => {
                AudioMgr.ins.playOneShot("audio/lose", 0.8);
                this.failPanel.active = true;
                this.failPanel.getChildByName("daily_smallframe").getChildByName("scoreLabel").getComponent(Label).string = this.PlayerScore + "";
                if (localStorage.getItem("maxScore")) {
                    this.failPanel.getChildByName("samll_form").getChildByName("maxScoreLabel").getComponent(Label).string = JSON.parse(localStorage.getItem("maxScore"));
                }

                if (localStorage.getItem("maxScore")) {
                    if (JSON.parse(localStorage.getItem("maxScore")) < this.PlayerScore) {
                        localStorage.setItem("maxScore", JSON.stringify(this.PlayerScore))
                    }
                }
                else {
                    localStorage.setItem("maxScore", JSON.stringify(this.PlayerScore))
                }



            }, 1000);

        }

    }

    onclickReviveBtn() {
        Adsdk.instance.showVideo(() => {
            this.failPanel.active = false;
            let pos1 = this.currStandBlock.getPosition();
            this.player.getChildByName("sp").getComponent(dragonBones.ArmatureDisplay).playAnimation("stand", 0);
            this.player.getComponent(RigidBody2D).linearVelocity = v2(0, 0);
            this.player.getComponent(RigidBody2D).type = ERigidBody2DType.Kinematic;
            this.player.setPosition(v3(pos1.x, pos1.y + 90, 0));
            this.isGameIng = true;

            this.gameReSet();
        }, () => {

        })

    }

    onclickHomeBtn() {
        AudioMgr.ins.playOneShot("audio/click", 0.8);

        director.loadScene("start")

    }

    onclickRestartBtn() {
        AudioMgr.ins.playOneShot("audio/click", 0.8);

        director.loadScene("singleGame")

    }
    onclickContinueBtn() {
        AudioMgr.ins.playOneShot("audio/click", 0.8);

        this.pausePanel.active = false;

    }
    onclickPauseBtn() {
        Adsdk.instance.showInterstitialAd();

        AudioMgr.ins.playOneShot("audio/click", 0.8);

        this.pausePanel.active = true;
        this.renewAudioUI();

    }

    createMinStr(pos, str) {
        let pre = instantiate(this.minTipPre);
        pre.setParent(this.minTipRoot);
        pre.setPosition(pos.x, pos.y);
        pre.getChildByName("Label").getComponent(Label).string = str;
        tween(pre)
            .by(0.7, { position: v3(0, 80, 0) })
            .call(() => {
                pre.destroy();
            })
            .start()
    }


    onclickSetPanelaudioEffectBtn() {
        if (UserInfo.isAudioEffect) {
            UserInfo.isAudioEffect = false;
        }
        else {
            UserInfo.isAudioEffect = true;
        }

        this.renewAudioUI();
    }
    onclickSetPanelmusicBtn() {
        if (UserInfo.isAudioBgm) {
            UserInfo.isAudioBgm = false;
            AudioMgr.ins.stop();
        }
        else {
            UserInfo.isAudioBgm = true;
            AudioMgr.ins.play("audio/bgm");
        }
        this.renewAudioUI();

    }


    renewAudioUI() {
        if (UserInfo.isAudioBgm) {
            resources.load("audioImg/musicOn/spriteFrame", SpriteFrame, (err, res) => {
                this.pausePanel.getChildByName("bgmBtn").getChildByName("sp").getComponent(Sprite).spriteFrame = res;

            })
        }
        else {
            resources.load("audioImg/musicOff/spriteFrame", SpriteFrame, (err, res) => {
                this.pausePanel.getChildByName("bgmBtn").getChildByName("sp").getComponent(Sprite).spriteFrame = res;

            })
        }

        if (UserInfo.isAudioEffect) {
            resources.load("audioImg/effectOn/spriteFrame", SpriteFrame, (err, res) => {
                this.pausePanel.getChildByName("effectBtn").getChildByName("sp").getComponent(Sprite).spriteFrame = res;

            })
        }
        else {
            resources.load("audioImg/effectOff/spriteFrame", SpriteFrame, (err, res) => {
                this.pausePanel.getChildByName("effectBtn").getChildByName("sp").getComponent(Sprite).spriteFrame = res;

            })
        }
    }


}


